﻿using UnityEngine;
using System.Collections;

public class ABLoader : MonoBehaviour 
{

    //总的Manifest文件名称
    public string _MainManifestName = "StreamingAssets";
    //要加载的AB名称
    public string _assetBundleManifestName = "cube_ab.ab1";

   // public string _AB_Path = "/StreamingAssets/";

    public int version_id = 0;

    public string abPath;

    void Awake()
    {
        abPath =
#if UNITY_ANDROID
		"jar:file://" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE
		Application.dataPath + "/Raw/";
#elif UNITY_EDITOR
    "file://" + Application.dataPath + "/StreamingAssets/";
#elif UNITY_STANDALONE_WIN
      "http://sinacloud.net/unity-ab-test-1/ab/";
#else
        string.Empty;
#endif
    }

    IEnumerator DownloadAB()
    {
        //AB所在的路径
        //string abPath = "file://" + Application.dataPath + _AB_Path;

        //manifest文件所在路径
        string manifestPath = abPath + _MainManifestName;

        //先加载manifest文件
        WWW wwwManifest = WWW.LoadFromCacheOrDownload(manifestPath, version_id);

        yield return wwwManifest;

        //如果AB之间存在依赖关系，要先加载总的Manifest文件，通过Manifest文件加载对应的依赖文件，然后再加载要加载的AB

        if (wwwManifest.error == null)
        {
            AssetBundle mainfestBundle = wwwManifest.assetBundle;

            AssetBundleManifest mainfest = (AssetBundleManifest)mainfestBundle.LoadAsset("AssetBundleManifest");//该名称是固定的
            mainfestBundle.Unload(false);

            //获取依赖文件列表
            string[] dependentABs = mainfest.GetAllDependencies(_assetBundleManifestName);
            AssetBundle[] abs = new AssetBundle[dependentABs.Length];
            //for (int i = 0; i < abs.Length; i++)
            //{
            //    //加载所有依赖文件
            //    WWW www = WWW.LoadFromCacheOrDownload(abPath + dependentABs[i], version_id);
            //    yield return www;
            //    abs[i] = www.assetBundle;
            //}

            /*
            编辑器模式下运行AssetBundleTest, 从网上下载的ab会缓存在以下目录：
            C:\Users\Administrator\AppData\LocalLow\Unity\WebPlayer\Cache\DefaultCompany_AssetBundleTest
            */

            //加载需要的文件
            WWW www2 = WWW.LoadFromCacheOrDownload(abPath + _assetBundleManifestName, version_id);
            yield return www2;
            AssetBundle ab = www2.assetBundle;
            if(ab != null)
            {
               StartCoroutine(StartLoadAssets(ab));
            }
        }
        else
        {
            Debug.Log(wwwManifest.error);
        }
    }

    IEnumerator DownloadAllAB()
    {
        //AB所在的路径
        //string abPath = "file://" + Application.dataPath + _AB_Path;

        //manifest文件所在路径
        string manifestPath = abPath + _MainManifestName;

        strLog += "manifestPath = " + manifestPath + "\n";

        //先加载manifest文件
        WWW wwwManifest = WWW.LoadFromCacheOrDownload(manifestPath, version_id);

        yield return wwwManifest;

        //如果AB之间存在依赖关系，要先加载总的Manifest文件，通过Manifest文件加载对应的依赖文件，然后再加载要加载的AB

        if (wwwManifest.error == null)
        {
            AssetBundle mainfestBundle = wwwManifest.assetBundle;

            AssetBundleManifest mainfest = (AssetBundleManifest)mainfestBundle.LoadAsset("AssetBundleManifest");//该名称是固定的
            mainfestBundle.Unload(false);

            string[] allAB = mainfest.GetAllAssetBundles();
            string[] allAB_WithMainfestName = mainfest.GetAllAssetBundlesWithVariant();

            for (int i = 0; i < allAB.Length; i++)
            {
                //获取依赖文件列表
                //string[] dependentABs = mainfest.GetAllDependencies(allAB[i]);
                //AssetBundle[] abs = new AssetBundle[dependentABs.Length];
                //for (int j = 0; j < abs.Length; j++)
                //{
                //    //加载所有依赖文件
                //    WWW www = WWW.LoadFromCacheOrDownload(abPath + dependentABs[j], version_id);
                //    yield return www;
                //    abs[j] = www.assetBundle;
                //}

                //加载需要的文件
                string fileName = abPath + allAB[i];
                WWW www2 = WWW.LoadFromCacheOrDownload(fileName, version_id);

                strLog += "abFilePath = "+ fileName + "\n";

                yield return www2;
                AssetBundle ab = www2.assetBundle;
                if (ab != null)
                {
                    StartCoroutine(StartLoadAssets(ab));
                }
            }
        }
        else
        {
            strLog += "err = " + wwwManifest.error+"\n";
            Debug.Log(wwwManifest.error);
        }
    }

    IEnumerator StartLoadAssets(AssetBundle ab)
    {
        //WWW www = WWW.LoadFromCacheOrDownload(url, 1);
        //yield return www;

        //AssetBundle ab = www.assetBundle;

        //异步加载对象
        //AssetBundleRequest req = ab.LoadAssetAsync("myObject", typeof(GameObject));
        AssetBundleRequest req = ab.LoadAllAssetsAsync(typeof(GameObject));

        //等待异步完成
        yield return req;

        //获得加载对象的引用
        //GameObject obj = req.asset as GameObject;
        // req.allAssets
        for (int i = 0; i < req.allAssets.Length; i++)
        {
            GameObject o = GameObject.Instantiate(req.allAssets[i]) as GameObject;
            
        }

        //从内存中卸载AB
        ab.Unload(false);
    }

    string strLog = "";

    void OnGUI()
    {
        if( GUI.Button(new Rect(0, 0, 300, 100), "SetABUrl"))
        {
            abPath = "https://sinacloud.net/unity-ab-test-1/ab/";
        }

        if (GUI.Button(new Rect(0, 150, 300, 100), "LoadAll"))
        {
            StartCoroutine(DownloadAllAB());
        }

        GUI.TextField(new Rect(0, 300, 1300, 100), strLog);
    }
}
